from my_loggers.baselogger import BaseLogger
from settings import BASE_DIR
import sys
import os

sys.path.append(os.path.dirname(BASE_DIR))
from my_loggers.configs import LOG_LEVEL
import sys
import datetime


class FileHandler(BaseLogger):
    def __init__(self, level, fmt=None, file=None):
        super().__init__(level, fmt)
        self.file = file
        if not self.file:
            self._file = sys.stdout
        else:
            self._file = open(file, 'w')
        if not self.fmt:
            self.fmt = "%Y-%m-%d %H:%M:%S"

    def __log_out(self, level, sender, massage):
        # 到达相应的日志基本才会输出
        if LOG_LEVEL[self.level] <= LOG_LEVEL[level]:
            log_msg = "发生时间:{}日志级别:{}产生日志文件:{}:消息:{}\n".format(datetime.datetime.now().strftime(self.fmt), level,
                                                               sender, massage)
            self._file.write(log_msg)
            """
            关闭handler
            """

    def __del__(self):
        self._file.close()

    def info(self, sender, msg):
        self.__log_out("info", sender, msg)

    def debug(self, sender, msg):
        self.__log_out("debug", sender, msg)

    def warn(self, sender, msg):
        self.__log_out("warn", sender, msg)

    def error(self, sender, msg):
        self.__log_out("error", sender, msg)


if __name__ == "__main__":
    logger = FileHandler("error")
    logger.warn('aaa', '错误')
    logger.info('aaa', '错误')
    logger.error('aaa', '错误')
    logger.debug('aaa', '错误')
